package com.yunhe.day322.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yunhe.day322.domain.Role;
import com.yunhe.day322.domain.UserInfo;
import com.yunhe.day322.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    /**
     * 新增用户
     * @param userInfo
     * @return
     */
    @RequestMapping("save")
    public String save(UserInfo userInfo){
        System.out.println(userInfo);
        userService.save(userInfo);
        return "redirect:findAll";
    }
    @RequestMapping("findAll")
    public String findAll(@RequestParam(value = "page", defaultValue = "1") Integer page , @RequestParam(value = "size",defaultValue = "5") Integer size, Model model){

        PageHelper.startPage(page,size);

        List<UserInfo> list =  this.userService.findAllUsers(page, size);
        PageInfo pageInfo = new PageInfo(list);


        model.addAttribute("pageInfo",pageInfo);
        return "user-list";
    }
    /**
     * 用户详情
     * @param id
     * @return
     */
    @GetMapping("findById")
    public String findById(@RequestParam("id") Integer id, Model model){
        UserInfo userInfo =  userService.findUserById(id);
        model.addAttribute("user",userInfo);
        return "user-show";
    }
    /**
     * 添加角色前。查询哪些角色可以添加
     * @param id
     * @return
     */
    @RequestMapping("findUserByIdAndAllRole")
    public String findUserByIdAndAllRole(@RequestParam("id") Integer id , Model model){
        //得知道给谁进行添加角色
        UserInfo userInfo = userService.findUserInfoById(id);
        model.addAttribute("user",userInfo);

        //根据用户id查询该用户哪些角色可以添加
        List<Role> roleList =  userService.findOtherRole(id);

        model.addAttribute("roleList",roleList);

        return "user-role-add";
    }
    @RequestMapping("addRoleToUser")
    public String addRoleToUser(@RequestParam("userId") Integer userId , @RequestParam("ids") Integer[] ids){
        this.userService.addRoleToUser(userId,ids);
        return "redirect:findAll";
    }
    @RequestMapping("deleteUser")
    public String deleteById(int id){
        userService.deleteUserRole(id);
        userService.deleteById(id);
        return "redirect:findAll";
    }

}
